package com.supostacks.xuetangerp.controller;

import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.supostacks.rpc.server.dto.BaseDto;
import com.supostacks.rpc.server.dto.FileManagementDto;
import com.supostacks.rpc.server.req.DeployReq;
import com.supostacks.rpc.server.res.XResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequestMapping("/file")
@RestController
public class FileController extends BaseController {
    @Override
    public BaseDto buildData(JSONObject json) {
        return JSONObject.toJavaObject(json, FileManagementDto.class);
    }

    @Override
    public BaseDto takeBaseDto() {
        return new FileManagementDto();
    }

    @RequestMapping("/upload/file")
    public SaResult uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("source") String source,
            @RequestParam("fileType") String fileType
    ) {
        try {
            FileManagementDto fileManagementDto = FileManagementDto.builder()
                    .fileType(fileType)
                    .fileData(file.getBytes())
                    .fileKey(source + "/" + file.getOriginalFilename()).build();

            DeployReq req = DeployReq.builder().data(fileManagementDto)
                    .type("insert").build();

            XResult result = dataDeployService.deploy(req);

            return SaResult.data(result.getResult()).setCode(result.getCode()).setMsg(result.getMsg());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
